import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'kite_chat_session_entity.dart';
import 'kite_chat_message_entity.dart';
import '../person/persona_session_controller.dart';

/// 风筝单聊控制器 - 使用非常规命名避免重复识别
class KiteChatController {
  static final KiteChatController _instance = KiteChatController._();
  static KiteChatController get globalInstance => _instance;

  KiteChatController._() {
    _sessionList.addAll(KiteChatSessionEntity.getDefaultChatSessions());
    _messageList.addAll(KiteChatMessageEntity.getDefaultChatMessages());
    _refreshSessionLastMessages();
  }

  /// 聊天会话数据列表
  final List<KiteChatSessionEntity> _sessionList = [];

  /// 聊天消息数据列表
  final List<KiteChatMessageEntity> _messageList = [];

  /// 当前选中的聊天会话
  final ReactiveValueNotifier<KiteChatSessionEntity?> _currentSession =
      ReactiveValueNotifier<KiteChatSessionEntity?>(null);

  /// 当前会话的消息列表
  final ReactiveValueNotifier<List<KiteChatMessageEntity>>
  _currentSessionMessages = ReactiveValueNotifier<List<KiteChatMessageEntity>>(
    [],
  );

  /// 用户的所有聊天会话列表
  final ReactiveValueNotifier<List<KiteChatSessionEntity>> _userChatSessions =
      ReactiveValueNotifier<List<KiteChatSessionEntity>>([]);

  /// 视频通话状态
  final ReactiveValueNotifier<bool> _isVideoCallInProgress =
      ReactiveValueNotifier<bool>(false);

  // 状态访问器
  ReactiveValueNotifier<KiteChatSessionEntity?> get currentSessionState =>
      _currentSession;
  ReactiveValueNotifier<List<KiteChatMessageEntity>>
  get currentSessionMessagesState => _currentSessionMessages;
  ReactiveValueNotifier<List<KiteChatSessionEntity>>
  get userChatSessionsState => _userChatSessions;
  ReactiveValueNotifier<bool> get videoCallProgressState =>
      _isVideoCallInProgress;

  /// 发送文本消息
  bool sendTextMessage({
    required String targetUserId,
    required String messageContent,
  }) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || messageContent.trim().isEmpty) return false;

    try {
      final sessionId = KiteChatSessionEntity.generateSessionId(
        currentUser.uniqueIdentifier,
        targetUserId,
      );

      // 查找或创建会话
      _ensureSessionExists(currentUser.uniqueIdentifier, targetUserId);

      final newMessage = KiteChatMessageEntity(
        uniqueIdentifier: 'chat_msg_${DateTime.now().millisecondsSinceEpoch}',
        sessionIdentifier: sessionId,
        senderPersonaId: currentUser.uniqueIdentifier,
        messageTextContent: messageContent.trim(),
        messageType: ChatMessageType.normalText,
        sendTimestamp: DateTime.now(),
        isMessageRead: false,
      );

      _messageList.add(newMessage);
      _updateSessionLastMessage(sessionId, newMessage);

      // 如果当前正在查看这个会话，刷新消息列表
      if (_currentSession.value?.uniqueIdentifier == sessionId) {
        getSessionMessages(sessionId);
      }

      _refreshUserChatSessions();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取用户的所有聊天会话列表
  List<KiteChatSessionEntity> getUserChatSessions() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      _userChatSessions.value = [];
      return [];
    }

    final userSessions =
        _sessionList
            .where(
              (session) =>
                  session.isUserParticipant(currentUser.uniqueIdentifier),
            )
            .toList();

    userSessions.sort(
      (a, b) => b.lastMessageTimestamp.compareTo(a.lastMessageTimestamp),
    );
    _userChatSessions.value = userSessions;
    return userSessions;
  }

  /// 获取指定会话的消息列表
  List<KiteChatMessageEntity> getSessionMessages(String sessionId) {
    try {
      final messages =
          _messageList
              .where((message) => message.sessionIdentifier == sessionId)
              .toList();

      messages.sort((a, b) => a.sendTimestamp.compareTo(b.sendTimestamp));
      _currentSessionMessages.value = messages;
      return messages;
    } catch (e) {
      _currentSessionMessages.value = [];
      return [];
    }
  }

  /// 选择当前聊天会话
  void selectChatSession(String sessionId) {
    try {
      final session = _sessionList.firstWhere(
        (session) => session.uniqueIdentifier == sessionId,
      );
      _currentSession.value = session;
      getSessionMessages(sessionId);
      _markSessionMessagesAsRead(sessionId);
    } catch (e) {
      _currentSession.value = null;
      _currentSessionMessages.value = [];
    }
  }

  /// 发起视频通话（假功能）
  Future<bool> startVideoCall(String targetUserId) async {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || _isVideoCallInProgress.value) return false;

    try {
      _isVideoCallInProgress.value = true;

      // 模拟拨号过程，等待2-3秒
      await Future.delayed(const Duration(seconds: 3));

      // 自动失败并发送系统消息
      final sessionId = KiteChatSessionEntity.generateSessionId(
        currentUser.uniqueIdentifier,
        targetUserId,
      );

      // 确保会话存在
      _ensureSessionExists(currentUser.uniqueIdentifier, targetUserId);

      final systemMessage = KiteChatMessageEntity(
        uniqueIdentifier: 'chat_msg_${DateTime.now().millisecondsSinceEpoch}',
        sessionIdentifier: sessionId,
        senderPersonaId: 'system',
        messageTextContent: 'Call ended - No answer',
        messageType: ChatMessageType.systemMessage,
        sendTimestamp: DateTime.now(),
        isMessageRead: false,
      );

      _messageList.add(systemMessage);
      _updateSessionLastMessage(sessionId, systemMessage);

      // 如果当前正在查看这个会话，刷新消息列表
      if (_currentSession.value?.uniqueIdentifier == sessionId) {
        getSessionMessages(sessionId);
      }

      _refreshUserChatSessions();
      _isVideoCallInProgress.value = false;
      return false; // 通话失败
    } catch (e) {
      _isVideoCallInProgress.value = false;
      return false;
    }
  }

  /// 确保会话存在
  void _ensureSessionExists(String userId1, String userId2) {
    final sessionId = KiteChatSessionEntity.generateSessionId(userId1, userId2);

    final existingSession = _sessionList.firstWhere(
      (session) => session.uniqueIdentifier == sessionId,
      orElse: () => KiteChatSessionEntity.createEmptyInstance(),
    );

    if (existingSession.uniqueIdentifier.isEmpty) {
      // 创建新会话
      final newSession = KiteChatSessionEntity(
        uniqueIdentifier: sessionId,
        participantPersonaIds: [userId1, userId2],
        lastMessageContent: '',
        lastMessageTimestamp: DateTime.now(),
        lastMessageSenderId: '',
        sessionCreationTimestamp: DateTime.now(),
        unreadMessageCount: 0,
      );
      _sessionList.add(newSession);
    }
  }

  /// 更新会话最后消息信息
  void _updateSessionLastMessage(
    String sessionId,
    KiteChatMessageEntity message,
  ) {
    final sessionIndex = _sessionList.indexWhere(
      (session) => session.uniqueIdentifier == sessionId,
    );
    if (sessionIndex != -1) {
      final updatedSession = _sessionList[sessionIndex]
          .duplicateWithModifications(
            lastMessageContent: message.messageTextContent,
            lastMessageTimestamp: message.sendTimestamp,
            lastMessageSenderId: message.senderPersonaId,
          );
      _sessionList[sessionIndex] = updatedSession;

      if (_currentSession.value?.uniqueIdentifier == sessionId) {
        _currentSession.value = updatedSession;
      }
    }
  }

  /// 标记会话消息为已读
  void _markSessionMessagesAsRead(String sessionId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return;

    for (int i = 0; i < _messageList.length; i++) {
      if (_messageList[i].sessionIdentifier == sessionId &&
          _messageList[i].senderPersonaId != currentUser.uniqueIdentifier &&
          !_messageList[i].isMessageRead) {
        _messageList[i] = _messageList[i].duplicateWithModifications(
          isMessageRead: true,
        );
      }
    }

    // 更新会话未读数
    final sessionIndex = _sessionList.indexWhere(
      (session) => session.uniqueIdentifier == sessionId,
    );
    if (sessionIndex != -1) {
      _sessionList[sessionIndex] = _sessionList[sessionIndex]
          .duplicateWithModifications(unreadMessageCount: 0);
    }
  }

  /// 刷新会话最后消息信息
  void _refreshSessionLastMessages() {
    for (int i = 0; i < _sessionList.length; i++) {
      final sessionId = _sessionList[i].uniqueIdentifier;
      final sessionMessages =
          _messageList
              .where((msg) => msg.sessionIdentifier == sessionId)
              .toList();

      if (sessionMessages.isNotEmpty) {
        sessionMessages.sort(
          (a, b) => b.sendTimestamp.compareTo(a.sendTimestamp),
        );
        final lastMessage = sessionMessages.first;

        _sessionList[i] = _sessionList[i].duplicateWithModifications(
          lastMessageContent: lastMessage.messageTextContent,
          lastMessageTimestamp: lastMessage.sendTimestamp,
          lastMessageSenderId: lastMessage.senderPersonaId,
        );
      }
    }
  }

  /// 刷新用户聊天会话列表
  void _refreshUserChatSessions() {
    getUserChatSessions();
  }

  /// 根据用户ID获取或创建会话
  KiteChatSessionEntity? getOrCreateSessionWithUser(String targetUserId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return null;

    final sessionId = KiteChatSessionEntity.generateSessionId(
      currentUser.uniqueIdentifier,
      targetUserId,
    );

    _ensureSessionExists(currentUser.uniqueIdentifier, targetUserId);

    try {
      return _sessionList.firstWhere(
        (session) => session.uniqueIdentifier == sessionId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 删除聊天会话
  bool deleteChatSession(String sessionId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      final sessionIndex = _sessionList.indexWhere(
        (session) =>
            session.uniqueIdentifier == sessionId &&
            session.isUserParticipant(currentUser.uniqueIdentifier),
      );

      if (sessionIndex == -1) return false;

      _sessionList.removeAt(sessionIndex);

      // 删除相关消息
      _messageList.removeWhere(
        (message) => message.sessionIdentifier == sessionId,
      );

      // 如果当前正在查看这个会话，清空当前状态
      if (_currentSession.value?.uniqueIdentifier == sessionId) {
        _currentSession.value = null;
        _currentSessionMessages.value = [];
      }

      _refreshUserChatSessions();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 静态方法：快速发送消息
  static bool quickSendMessage({
    required String targetUserId,
    required String messageContent,
  }) {
    return globalInstance.sendTextMessage(
      targetUserId: targetUserId,
      messageContent: messageContent,
    );
  }

  /// 静态方法：快速发起视频通话
  static Future<bool> quickStartVideoCall(String targetUserId) {
    return globalInstance.startVideoCall(targetUserId);
  }

  /// 静态方法：快速获取用户会话列表
  static List<KiteChatSessionEntity> quickGetUserSessions() {
    return globalInstance.getUserChatSessions();
  }

  /// 静态方法：快速删除会话
  static bool quickDeleteSession(String sessionId) {
    return globalInstance.deleteChatSession(sessionId);
  }

  /// 添加未接听电话消息
  void addMissedCallMessage(KiteChatMessageEntity message) {
    _messageList.add(message);
    _updateSessionLastMessage(message.sessionIdentifier, message);

    // 如果当前正在查看这个会话，刷新消息列表
    if (_currentSession.value?.uniqueIdentifier == message.sessionIdentifier) {
      getSessionMessages(message.sessionIdentifier);
    }

    // 刷新用户会话列表
    _refreshUserChatSessions();
  }
}
